<template>
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item label="车辆:" prop="truckCode">
        <el-select v-model="query.truckCode" filterable clearable :loading="$loadingPlugin.getVehicleList" placeholder="请选择">
          <el-option
            v-for="item in vehicleList"
            :key="item.truckId"
            :label="item.truckCode"
            :value="item.truckCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="司机/押运员:" prop="userId">
        <el-select v-model="query.userId" filterable clearable :loading="$loadingPlugin.getDriverList" placeholder="请选择">
          <el-option
            v-for="item in driverList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
        <el-button type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <add ref="add" :vehicle-list="vehicleList" />
  </div>
</template>

<script>
  import {
    queryTruckSettingList,
    truckQueryAllTruck,
    allDriverList,
    deleteVehicleSetting,
    queryExportVehicleSettingList, queryExportDomain
  } from '@/api'
  import { mapGetters } from 'vuex'
  import Add from './components/AddSetting'
  import { parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'

  export default {
    name: 'tab-setting',
    components: {
      Add
    },
    data() {
      return {
        exportDomain: '',
        vehicleList: [],
        driverList: [],
        query: {
          truckCode: '',
          userId: ''
        },
        tableData: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'truckCode',
              label: '车辆'
            },
            {
              prop: 'driverNames',
              label: '司机'
            },
            {
              prop: 'escortNames',
              label: '押运员'
            },
            {
              prop: 'modifyTime',
              label: '最后修改时间',
              render: (h, { row }) => <span>{ row.modifyTime && parseTime(row.modifyTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'remark',
              label: '备注'
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 85,
              render: (h, { row }) => {
                return (
                  <div>
                    <el-link underline={false} size='mini' onClick={() => this.update(row)}>编辑</el-link>
                    <el-link underline={false} size='mini' type='danger' onClick={() => this.del(row)}>删除</el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      await Promise.all([this.getExportDomain(), this.getVehicleList(), this.getDriverList()])
    },
    methods: {
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 获取车辆列表
      async getVehicleList() {
        const res = await truckQueryAllTruck({})
        this.vehicleList = res.data
      },
      // 获取司机列表
      async getDriverList() {
        const res = await allDriverList({})
        this.driverList = res.data
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        const res = await queryTruckSettingList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      async add() {
        this.getVehicleList()
        await this.$refs.add.open()
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async update(row) {
        await this.$refs.add.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 删除
      async del(row) {
        this.$confirm(`确定删除该车辆配置`, '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在执行操作',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          this.$refs.lbTable.fetch({ currentPage: 1 })
          deleteVehicleSetting({ truckCode: row.truckCode }).then(() => {
            this.$refs.lbTable.fetch({ currentPage: 1 })
            this.$notify({
              title: '提示',
              message: `删除成功`,
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryExportVehicleSettingList({
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      reset() {
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style scoped>

</style>
